#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>
#include<assert.h>
#include"ListNode.h"

void ListInit(LinkList* L)
{
	(*L)->next = (*L);
	(*L)->prev = (*L);
	(*L)->DataType = 0;
}

ListNode* BuyListNode(DataType x)
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	node->DataType = x;
	node->next = NULL;
	node->prev = NULL;
	return node; 
}

void ListPushBack(LinkList L, DataType x)
{
	assert(L);

	ListNode* tail = L->prev;
	ListNode* newnode = BuyListNode(x);
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = L;
	L->prev = newnode;
}

void ListPrint(LinkList L)
{
	assert(L);
	ListNode* cur = L->next;
	while (cur != L)
	{
		printf("%d ", cur->DataType);
		cur = cur->next;
	}
	printf("\n");
}

void ListPushFront(LinkList L, DataType x)
{
	assert(L);
	ListNode* newnode = BuyListNode(x);
	newnode->next = L->next;
	L->next->prev = newnode;
	newnode->prev = L;
	L->next = newnode;
}

void ListPopBack(LinkList L)
{
	assert(L);
	ListNode* tail = L->prev;
	if (tail != L)
	{
		L->prev = tail->prev;
		tail->prev->next = L;
		free(tail);
		tail = NULL;
	}
}

void ListPopFront(LinkList L)
{
	assert(L);
	ListNode* head = L->next;
	if (head != L)
	{
		L->next = head->next;
		head->next->prev = L;
		free(head);
		head = NULL;
	}
}

void ListDelete(LinkList L, DataType x)
{
	assert(L);
	ListNode* cur = L->next;

	while (cur != L)
	{
		ListNode* temp = cur->next;
		if (cur->DataType == x)
		{
			cur->prev->next = cur->next;
			cur->next->prev = cur->prev;
			free(cur);
			cur = NULL;
		}
		cur = temp;
	}
}

ListNode* ListFind(LinkList L, DataType x)
{
	assert(L);
	ListNode* cur = L->next;
	while (cur != L)
	{
		if (cur->DataType == x)
		{
			return cur;
		}
		cur = cur->next;
	}

	return NULL;
}

void ListInsert(ListNode* pos, DataType x)
{
	assert(pos);
	ListNode* newnode = BuyListNode(x);
	newnode->next = pos;
	newnode->prev = pos->prev;
	pos->prev->next = newnode;
	pos->prev = newnode;
}




